package com.itheima.itheima_health.task;

import com.itheima.itheima_health.constant.EmailConstant;
import com.itheima.itheima_health.constant.MessageConstant;
import com.itheima.itheima_health.constant.RedisConstant;
import com.itheima.itheima_health.entity.Result;
import com.itheima.itheima_health.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
/**
 * 定时任务类，定时处理
 */
public class Task {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private QiniuUtils qiniuUtils;
    //存储随机生成的校验码
    private String cdoe_store = null;
    @Autowired(required = false)
    // 引入Spring Mail依赖后，会自动装配到IOC容器
    private JavaMailSender sender;

    /**
     * 定时清理七牛云内的垃圾图片
     */
    //@Scheduled(cron = "0/30 * * * * ? ")
    public void processTime(){
        log.info("定时清理七牛云内的垃圾图片");
        //获取已上传的图片  跟  已经保存的图片的差值
        Set<String> difference = redisTemplate.opsForSet().difference(
                RedisConstant.SETMEAL_PIC_RESOURCES,
                RedisConstant.SETMEAL_PIC_DB_RESOURCES
        );

        //判断是否有垃圾图片
        if (difference == null || difference.isEmpty()){
            log.info("无垃圾图片");
        }else{
            //循环差值set集合删除每一张垃圾图片
            for (String value : difference) {
                log.info("删除七牛云垃圾文件:{}",value);
                //删除七牛云图片
                qiniuUtils.deleteFileFromQiniu(value);
                // 同步删除 Redis 中的垃圾图片记录
                redisTemplate.opsForSet().remove(RedisConstant.SETMEAL_PIC_RESOURCES, value);
            }
        }
    }
    //@Scheduled(cron = "0/15 * * * * ? ")
    public void email(){
        try {
            //生成6位随机数
            String code = (Math.random() + "").substring(2, 8);
            cdoe_store = code;
            //你想发给哪个邮箱
            String email = EmailConstant.RECEIVER_EMAIL;
            SimpleMailMessage message = new SimpleMailMessage();
            // 发送邮件的主题
            message.setSubject("悦生健康验证码");
            // 邮件的内容
            message.setText("您好，您正在操作敏感信息，需要核验您的身份,您收到的验证码为:" + code);
            // 指定要接收邮件的用户邮箱账号
            message.setTo(email);
            // 邮件发送方，也就是配置文件中的邮件地址。
            message.setFrom(EmailConstant.SENDER_EMAIL);
            sender.send(message); // 调用send方法发送邮件

            log.info("成功发送邮件至3104741394@qq.com");
        }catch (Exception e){
            log.info("发送邮件失败!");
        }
    }
}
